package fr.generali.sas.ws.v1_0;

import java.util.Date;

import javax.annotation.Resource;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import fr.generali.sas.ws.v1_0.service.PersistFlux;

public class SASIntegrationFluxServicesPortTypeImpl implements SASIntegrationFluxServicesPortType {

	private static final Logger LOGGER = LoggerFactory.getLogger(SASIntegrationFluxServicesPortTypeImpl.class);

	@Resource
	PersistFlux persistFlux;
	
	/**{@inheritDoc}
	 * @see fr.generali.sas.ws.v1_0.SASIntegrationFluxServicesPortType#checkService(fr.generali.sas.ws.v1_0.CheckServiceRequest)
	 */
	public CheckServiceResponse checkService(final CheckServiceRequest input) {
		LOGGER.info("Simple requete de type ping");
		final CheckServiceResponse response = new CheckServiceResponse();
		response.setPingDate(new Date());
		return response;
	}

	/**
	 * 
	 * @throws EligibiliteAdslFaultMsg
	 *             Si l'authentification échoue.
	 */
	protected void checkLoginPassword(final String login, final String password) throws SASIntegrationFaultMsg {
		// TODO implementer checkLoginPassword
	}

	/**{@inheritDoc}
	 * @see fr.generali.sas.ws.v1_0.SASIntegrationFluxServicesPortType#enregistreFlux(fr.generali.sas.ws.v1_0.IntegrationFluxRequest)
	 */
	public IntegrationFluxResponse enregistreFlux(final IntegrationFluxRequest input) throws SASIntegrationFaultMsg {
		// TODO Auto-generated method stub

		checkLoginPassword(input.getLogin(), input.getPassword());
		try {
			persistFlux.persistFlux(input.getFlux());
		} catch (Exception e) {
			//TODO (05/09/2011) a revoir car FUE (mainframe) ne peut rejouer et ne fera rien en cas d'erreur
			//il faut un mécanisme capable de rejouer l'appel
			//pb si bdd pas dispo pour enregistrer le flux => impossible de sauver le flux pour le rejouer
			LOGGER.error("Impossible de sauvegarder le flux "+input.getFlux(),e);
			final SASServerException sasEx = new SASServerException();
			//TODO define error code ?
			sasEx.setCode(1);
			sasEx.setDescription(ExceptionUtils.getMessage(e));
			throw new SASIntegrationFaultMsg("Impossible de sauvegarder le flux ", sasEx);			
		}
		final IntegrationFluxResponse reponse = new IntegrationFluxResponse();
		reponse.setIntegrationDate(new Date());
		reponse.setStatut(ReponseFermeeType.OK);

		return reponse;
	}

}
